<template>
  <div class="guidelines">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>简章分数</h1>
        <p>各院校招生简章和历年分数线信息</p>
      </div>

      <!-- 筛选条件 -->
      <div class="filters">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="招生简章" name="regulations"></el-tab-pane>
          <el-tab-pane label="历年分数" name="scores"></el-tab-pane>
        </el-tabs>
        
        <div class="filter-controls">
          <el-select
            v-model="selectedYear"
            placeholder="选择年份"
            style="width: 120px; margin-right: 16px;"
            @change="handleYearChange"
          >
            <el-option
              v-for="year in years"
              :key="year"
              :label="year + '年'"
              :value="year"
            />
          </el-select>
          
          <el-select
            v-model="selectedSchool"
            placeholder="选择院校"
            style="width: 200px; margin-right: 16px;"
            clearable
            filterable
            @change="handleSchoolChange"
          >
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
          
          <el-input
            v-model="keyword"
            placeholder="搜索关键词"
            style="width: 200px;"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-icon @click="handleSearch" style="cursor: pointer">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 招生简章列表 -->
      <div v-if="activeTab === 'regulations'" class="regulations-list" v-loading="loading">
        <div
          v-for="article in articles"
          :key="article.id"
          class="regulation-item"
          @click="goToArticle(article.id)"
        >
          <div class="regulation-info">
            <h3>{{ article.title }}</h3>
            <p v-if="article.summary">{{ article.summary }}</p>
            
            <div class="regulation-meta">
              <span class="school-name" v-if="article.schoolName">
                {{ article.schoolName }}
              </span>
              <span class="publish-date">
                {{ formatDate(article.publishTime) }}
              </span>
            </div>
          </div>
          
          <div class="regulation-actions">
            <el-button
              type="primary"
              size="small"
              @click.stop="goToArticle(article.id)"
            >
              查看详情
            </el-button>
            
            <el-button
              v-if="article.externalUrl"
              type="default"
              size="small"
              @click.stop="openExternal(article.externalUrl)"
            >
              外部链接
            </el-button>
          </div>
        </div>
        
        <!-- 暂无数据 -->
        <div v-if="!loading && !articles.length" class="empty">
          <el-empty description="暂无招生简章数据" />
        </div>
      </div>

      <!-- 历年分数列表 -->
      <div v-else class="scores-list" v-loading="loading">
        <!-- 分数线表格 -->
        <el-table :data="scoreLines" stripe>
          <el-table-column prop="schoolName" label="院校名称" min-width="200" />
          <el-table-column prop="majorName" label="专业名称" min-width="150" />
          <el-table-column prop="year" label="年份" width="80" />
          <el-table-column prop="scoreType" label="分数类型" width="100">
            <template #default="{ row }">
              <el-tag :type="row.scoreType === 'admission' ? 'primary' : 'success'">
                {{ row.scoreType === 'admission' ? '入围线' : '录取线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="minScore" label="最低分" width="80" />
          <el-table-column prop="maxScore" label="最高分" width="80" />
          <el-table-column prop="avgScore" label="平均分" width="80" />
          <el-table-column prop="enrollmentCount" label="录取人数" width="100" />
          <el-table-column prop="applicantCount" label="报名人数" width="100" />
          <el-table-column label="录取率" width="80">
            <template #default="{ row }">
              <span v-if="row.enrollmentCount && row.applicantCount">
                {{ ((row.enrollmentCount / row.applicantCount) * 100).toFixed(1) }}%
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 暂无数据 -->
        <div v-if="!loading && !scoreLines.length" class="empty">
          <el-empty description="暂无分数线数据" />
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { useArticleStore } from '@/stores/article'
import { useSchoolStore } from '@/stores/school'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const articleStore = useArticleStore()
const schoolStore = useSchoolStore()

// 当前激活的标签
const activeTab = ref('regulations')

// 筛选条件
const selectedYear = ref(new Date().getFullYear())
const selectedSchool = ref('')
const keyword = ref('')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 数据
const articles = ref([])
const scoreLines = ref([])
const schools = computed(() => schoolStore.schools)

// 年份选项
const years = computed(() => {
  const currentYear = new Date().getFullYear()
  return Array.from({ length: 5 }, (_, i) => currentYear - i)
})

// 标签切换处理
const handleTabChange = (tab) => {
  activeTab.value = tab
  currentPage.value = 1
  if (tab === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

// 年份变化处理
const handleYearChange = () => {
  currentPage.value = 1
  if (activeTab.value === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

// 院校变化处理
const handleSchoolChange = () => {
  currentPage.value = 1
  if (activeTab.value === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  if (activeTab.value === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  if (activeTab.value === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  if (activeTab.value === 'regulations') {
    fetchArticles()
  } else {
    fetchScoreLines()
  }
}

// 获取文章列表
const fetchArticles = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      categoryCode: 'regulations',
      schoolId: selectedSchool.value,
      keyword: keyword.value
    }
    
    const result = await articleStore.fetchArticles(params)
    articles.value = result.list || []
    total.value = result.total || 0
  } catch (error) {
    console.error('获取文章列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分数线列表 (模拟数据，实际需要后端API)
const fetchScoreLines = async () => {
  try {
    loading.value = true
    // 这里应该调用分数线API，暂时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    scoreLines.value = [
      {
        schoolName: '浙江纺织服装职业技术学院',
        majorName: '服装设计与工艺',
        year: 2024,
        scoreType: 'admission',
        minScore: 320,
        maxScore: 480,
        avgScore: 400,
        enrollmentCount: 30,
        applicantCount: 120
      },
      {
        schoolName: '杭州职业技术学院',
        majorName: '计算机应用技术',
        year: 2024,
        scoreType: 'final',
        minScore: 380,
        maxScore: 520,
        avgScore: 450,
        enrollmentCount: 40,
        applicantCount: 150
      }
      // 更多模拟数据...
    ]
    
    total.value = scoreLines.value.length
  } catch (error) {
    console.error('获取分数线失败:', error)
  } finally {
    loading.value = false
  }
}

// 跳转到文章详情
const goToArticle = (id) => {
  router.push(`/articles/${id}`)
}

// 打开外部链接
const openExternal = (url) => {
  window.open(url, '_blank')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 页面初始化
onMounted(async () => {
  await schoolStore.fetchSchools({ size: 100 })
  fetchArticles()
})
</script>

<style lang="scss" scoped>
.guidelines {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
  background: #f8f9fa;
  
  .page-header {
    text-align: center;
    margin-bottom: 40px;
    
    h1 {
      font-size: 32px;
      color: #333;
      margin-bottom: 8px;
    }
    
    p {
      color: #666;
      font-size: 16px;
    }
  }
  
  .filters {
    background: white;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    
    .filter-controls {
      display: flex;
      align-items: center;
      margin-top: 20px;
      flex-wrap: wrap;
      gap: 16px;
    }
  }
  
  .regulations-list {
    .regulation-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: white;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 16px;
      cursor: pointer;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
      }
      
      .regulation-info {
        flex: 1;
        
        h3 {
          font-size: 16px;
          color: #333;
          margin-bottom: 8px;
          line-height: 1.4;
        }
        
        p {
          color: #666;
          font-size: 14px;
          margin-bottom: 12px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .regulation-meta {
          display: flex;
          align-items: center;
          gap: 16px;
          
          .school-name {
            color: #409eff;
            font-size: 14px;
          }
          
          .publish-date {
            color: #999;
            font-size: 12px;
          }
        }
      }
      
      .regulation-actions {
        display: flex;
        gap: 8px;
        margin-left: 20px;
      }
    }
  }
  
  .scores-list {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .guidelines {
    padding: 20px 0;
    
    .page-header {
      margin-bottom: 20px;
      
      h1 {
        font-size: 24px;
      }
    }
    
    .filters {
      padding: 16px;
      margin-bottom: 20px;
      
      .filter-controls {
        flex-direction: column;
        align-items: stretch;
        
        .el-select,
        .el-input {
          width: 100% !important;
        }
      }
    }
    
    .regulations-list {
      .regulation-item {
        flex-direction: column;
        align-items: stretch;
        padding: 16px;
        
        .regulation-actions {
          margin-left: 0;
          margin-top: 16px;
          justify-content: flex-end;
        }
      }
    }
  }
}
</style>